﻿/*
 * Catalyst - http://catalystobjects.com
 * 
 * New BSD License (BSD)
 * 
 * Copyright (c) 2009, Ashley Brener
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 * 
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 * 
 * Neither the name of Midlet Earth nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.SqlClient;
using System.Text;
using SubSonic;
using System.Data;

namespace Catalyst
{
	public class Tools
	{
		public T ConvertType<T>(object obj)
		{
			Type type = typeof(T);

			if (type.BaseType == typeof(Enum))
			{
				return (T)Enum.Parse(type, obj.ToString(), true);
			}

			if (obj.GetType() == typeof(T))
			{
				return (T)obj;
			}

			if (isNullable(type) || type == typeof(object))
			{
				return (T)obj;
			}

			Type valType = obj.GetType();
			if (valType == typeof(Byte[]))
			{
				return (T)Convert.ChangeType(obj, valType);
			}

			return (T)Convert.ChangeType(obj, type);
		}

		private bool isNullable(Type objType)
		{
			if (!objType.IsGenericType)
			{
				return false;
			}
			return objType.GetGenericTypeDefinition().Equals(typeof(Nullable<>));
		}

		public class Data
		{
			#region *** CreateWhere ***
			public static Where CreateWhere(string ColumnName, object ParameterValue)
			{
				return CreateWhere(ColumnName, Comparison.Equals, ParameterValue);
			}

			public static Where CreateWhere(string ColumnName, Comparison Comparison, object ParameterValue)
			{
				Where where = new Where();
				where.ColumnName = ColumnName;
				where.Comparison = Comparison;
				where.ParameterValue = ParameterValue;

				return where;
			}
			#endregion

			#region *** GetInObjects ***
			public static object[] GetInObjects(TableSchema.Table Schema, string ColumnName)
			{
				List<Where> whereClauses = null;

				return GetInObjects(Schema, ColumnName, whereClauses);
			}

			public static object[] GetInObjects(TableSchema.Table Schema, string ColumnName, Where WhereClause)
			{
				List<Where> whereClauses = null;

				if (WhereClause != null)
				{
					whereClauses = new List<Where>();
					whereClauses.Add(WhereClause);
				}

				return GetInObjects(Schema, ColumnName, whereClauses);
			}

			public static object[] GetInObjects(TableSchema.Table Schema, string ColumnName, List<Where> WhereClauses)
			{
				Query query = new Query(Schema);

				if (WhereClauses != null && WhereClauses.Count > 0)
				{
					foreach (Where where in WhereClauses)
					{
						query.AddWhere(where);
					}
				}

				return GetInObjects(query, ColumnName);
			}

			public static object[] GetInObjects(Query Query, string ColumnName)
			{
				Query.IsDistinct = true;
				Query.ORDER_BY(ColumnName);

				List<object> inObjects = new List<object>();

				IDataReader reader = null;

				try
				{
					reader = Query.ExecuteReader();

					while (reader.Read())
					{
						if (!inObjects.Contains(reader[ColumnName]))
						{
							inObjects.Add(reader[ColumnName]);
						}
					}
				}
				finally
				{
					if (reader != null)
					{
						reader.Close();
					}
				}

				return inObjects.ToArray();
			}
			#endregion

			#region *** SaveAsync ***
			private SqlCommand sqlCommand;

			public IAsyncResult BeginSaveAsync<T>(string AsyncProviderName, ActiveRecord<T> DAORecord, AsyncCallback callback, object stateObject) where T : ActiveRecord<T>, new()
			{
				DataProvider provider = DataService.GetInstance(AsyncProviderName);

				List<string> tableNames = new List<string>(provider.GetTableNameList());

				SubSonic.TableSchema.Table table = DAORecord.GetSchema();

				if (!tableNames.Contains(table.TableName))
				{
					provider.AddSchema(table.TableName, table);
				}

				SqlConnection connection = (SqlConnection)new SharedDbConnectionScope(provider).CurrentConnection;

				QueryCommand queryCommand = DAORecord.GetSaveCommand();

				sqlCommand = new SqlCommand(queryCommand.CommandSql, connection);

				addSqlParameters(sqlCommand, queryCommand);

				return sqlCommand.BeginExecuteReader(callback, stateObject);
			}

			public void EndSaveAsync<T>(ActiveRecord<T> DAORecord, IAsyncResult asyncResult) where T : ActiveRecord<T>, new()
			{
				SqlDataReader reader = null;

				try
				{
					using (reader = sqlCommand.EndExecuteReader(asyncResult))
					{
						if (reader.Read())
						{
							DAORecord.GetColumnSettings().SetValue(DAORecord.GetSchema().PrimaryKey.ColumnName, reader["newId"]);
						}
					}
				}
				finally
				{
					if (reader != null)
					{
						reader.Close();
					}
				}
			}

			#endregion

			#region *** TransactionalSave ***

			public static int TransactionalSave<T>(ActiveRecord<T> DAORecord, SqlConnection TransactionalConnection, SqlTransaction Transaction) where T : ActiveRecord<T>, new()
			{
				int returnValue = -1;

				//Convert to a SQL Server command...
				QueryCommand queryCommand = DAORecord.GetSaveCommand();

				SqlCommand sqlCommand = new SqlCommand(queryCommand.CommandSql, TransactionalConnection);

				if (Transaction != null)
				{
					sqlCommand.Transaction = Transaction;
				}

				addSqlParameters(sqlCommand, queryCommand);

				object obj = sqlCommand.ExecuteScalar();

				if (obj != null && obj != DBNull.Value)
				{
					returnValue = (int)obj;
				}

				return returnValue;
			}

			#endregion

			private static void addSqlParameters(SqlCommand SqlCommand, QueryCommand QueryCommand)
			{
				if (QueryCommand.Parameters != null)
				{
					foreach (QueryParameter param in QueryCommand.Parameters)
					{
						SqlParameter sqlParameter = new SqlParameter(param.ParameterName, SubSonic.Utilities.Utility.GetSqlDBType(param.DataType));
						sqlParameter.Direction = param.Mode;

						//output parameters need to define a size
						//our default is 50
						if (sqlParameter.Direction == ParameterDirection.Output || sqlParameter.Direction == ParameterDirection.InputOutput)
						{
							sqlParameter.Size = param.Size;
						}

						//fix for NULLs as parameter values
						if (param.ParameterValue == null || SubSonic.Utilities.Utility.IsMatch(param.ParameterValue.ToString(), "null"))
						{
							sqlParameter.Value = DBNull.Value;
						}
						else if (param.DataType == DbType.Guid)
						{
							string paramValue = param.ParameterValue.ToString();

							if (!String.IsNullOrEmpty(paramValue))
							{
								if (!SubSonic.Utilities.Utility.IsMatch(paramValue, SqlSchemaVariable.DEFAULT))
								{
									sqlParameter.Value = new Guid(param.ParameterValue.ToString());
								}
							}
							else
							{
								sqlParameter.Value = DBNull.Value;
							}
						}
						else
						{
							sqlParameter.Value = param.ParameterValue;
						}

						SqlCommand.Parameters.Add(sqlParameter);
					}
				}
			}
		}
	}
}
